package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.item.dto.CategoryDTO;
import com.leyou.item.entity.TbCategory;
import com.leyou.item.mapper.TbCategoryMapper;
import com.leyou.item.service.TbCategoryService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * <p>
 * 商品类目表，类目和商品(spu)是一对多关系，类目与品牌是多对多关系 服务实现类
 * </p>
 *
 * @author HM
 * @since 2020-10-07
 */
@Service
public class TbCategoryServiceImpl extends ServiceImpl<TbCategoryMapper, TbCategory> implements TbCategoryService {

    /**
     * 根据父id 查询分类集合
     * @param parentId
     * @return
     */
    @Override
    public List<CategoryDTO> findCategoryListByPid(Long parentId) {
//        select * from tb_category where parent_id=?
//        构造条件
        QueryWrapper<TbCategory> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("parent_id",parentId);
        queryWrapper.lambda().eq(TbCategory::getParentId,parentId);
//          查询集合
        List<TbCategory> tbCategoryList = list(queryWrapper);
//        判断是否为空
        if(CollectionUtils.isEmpty(tbCategoryList)){
            throw new LyException(ExceptionEnum.CATEGORY_NOT_FOUND);
        }
//        对象转换
        List<CategoryDTO> categoryDTOList = BeanHelper.copyWithCollection(tbCategoryList, CategoryDTO.class);
        return categoryDTOList;
    }

    /**
     * 根据品牌id查询分类集合
     * @param brandId
     * @return
     */
    @Override
    public List<CategoryDTO> findCategoryListByBrandId(Long brandId) {
//        获取当前service对应的mapper接口
        List<TbCategory> tbCategoryList = this.getBaseMapper().selectListByBrandId(brandId);
        if(CollectionUtils.isEmpty(tbCategoryList)){
            throw new LyException(ExceptionEnum.CATEGORY_NOT_FOUND);
        }
        return BeanHelper.copyWithCollection(tbCategoryList,CategoryDTO.class);
    }
}
